package com.lizard.schedule.ui.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.wearable.view.WearableListView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.wearable.DataApi;
import com.google.android.gms.wearable.DataItem;
import com.google.android.gms.wearable.DataMap;
import com.google.android.gms.wearable.DataMapItem;
import com.google.android.gms.wearable.Node;
import com.google.android.gms.wearable.NodeApi;
import com.google.android.gms.wearable.PutDataMapRequest;
import com.google.android.gms.wearable.PutDataRequest;
import com.google.android.gms.wearable.Wearable;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lizard.schedule.R;
import com.lizard.schedule.consts.Path;
import com.lizard.schedule.manager.ObserverIfaces;
import com.lizard.schedule.manager.ObserverManager;
import com.lizard.schedule.model.WearSchedule;
import com.lizard.schedule.ui.activity.adapter.ScheduleListAdapter;
import com.lizard.schedule.ui.activity.base.BaseGoogleApiClientActivity;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends BaseGoogleApiClientActivity {

    private Handler handler;

    private WearableListView scheduleListV;

    private ScheduleListAdapter scheduleListAdapter;

    private ProgressBar progressBar;

    private TextView errorTv;

    boolean hasRequestSchedules = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        handler = new Handler();

        initView();

        ObserverManager.getInstance().addOnSyncSchedulesListener(onSyncSchedulesListener);

//        mock();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        ObserverManager.getInstance().removeOnSyncSchedulesListener(onSyncSchedulesListener);
    }

    /**
     * googleApiClient连接成功
     *
     * @param bundle
     */
    @Override
    public void onConnected(Bundle bundle) {
        super.onConnected(bundle);

        if (!hasRequestSchedules) {

            PendingResult<NodeApi.GetConnectedNodesResult> pendingResult = Wearable.NodeApi.getConnectedNodes(googleApiClient);
            pendingResult.setResultCallback(new ResultCallback<NodeApi.GetConnectedNodesResult>() {
                @Override
                public void onResult(final NodeApi.GetConnectedNodesResult getConnectedNodesResult) {

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            boolean hasNode = false;
                            List<Node> nodes = getConnectedNodesResult.getNodes();
                            for(Node node : nodes){
                                hasNode = true;
                                break;
                            }

                            if(hasNode){
                                requestSchedules();
                            } else{ // 未连接设备
                                showErrorTv(getString(R.string.check_connect), null);
                            }
                        }
                    });
                }
            });

        }
    }

    private void initView() {
        scheduleListV = (WearableListView) findViewById(R.id.schedule_list);
        scheduleListAdapter = new ScheduleListAdapter(this);
        scheduleListV.setAdapter(scheduleListAdapter);
        scheduleListV.setClickListener(new WearableListView.ClickListener() {
            @Override
            public void onClick(WearableListView.ViewHolder viewHolder) {
                WearSchedule wearSchedule = scheduleListAdapter.getItem(viewHolder.getAdapterPosition());
                Intent intent = new Intent(MainActivity.this, ScheduleDetailActivity.class);
                intent.putExtra(ScheduleDetailActivity.PARAM_DETAIL, wearSchedule);
                startActivity(intent);
            }

            @Override
            public void onTopEmptyRegionClick() {
            }

        });
        progressBar = (ProgressBar) findViewById(R.id.progress_bar);
        errorTv = (TextView) findViewById(R.id.error_tv);
    }

    private void mock() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                hideProgressBar();
                hideErrorTv();

                List<WearSchedule> wearSchedules = new ArrayList<>();

                WearSchedule wearSchedule = new WearSchedule();
                wearSchedule.setContentText("1dapter provides a set of pagesdapter provides a set of pages to podapter provides a setdapter provides a set of pages to podapter provides a setdapter provides a set of pages to podapter provides a setdapter provides a set of pages to podapter provides a setdapter provides a set of pages to podapter provides a setdapter provides a set of pages to podapter provides a setdapter provides a set of pages to podapter provides a set to podapter provides a set of pages to podapter provides a set of pages to po");
                wearSchedule.setDateStr("2001-1-1");
                wearSchedule.setTimeStr("17:00");
                wearSchedules.add(wearSchedule);

                wearSchedule = new WearSchedule();
                wearSchedule.setContentText("2da");
                wearSchedule.setDateStr("2001-1-1");
                wearSchedule.setTimeStr("17:00");
                wearSchedules.add(wearSchedule);

                wearSchedule = new WearSchedule();
                wearSchedule.setContentText("3dapter provides a set of pages to podapter provides a set of pages to podapter provides a set of pages to po");
                wearSchedule.setDateStr("2001-1-1");
                wearSchedule.setTimeStr("17:00");
                wearSchedules.add(wearSchedule);

                wearSchedule = new WearSchedule();
                wearSchedule.setContentText("4dapter provides a set of pages to podapter provides a set of pages to podapter provides a set of pages to po");
                wearSchedule.setDateStr("2001-1-1");
                wearSchedule.setTimeStr("17:00");
                wearSchedules.add(wearSchedule);

                scheduleListAdapter.setData(wearSchedules);
            }
        }, 1000);
    }

    private void showProgressBar() {
        handler.post(new Runnable() {
            @Override
            public void run() {
                hideErrorTv();
                progressBar.setVisibility(View.VISIBLE);
            }
        });
    }

    private void hideProgressBar() {
        handler.post(new Runnable() {
            @Override
            public void run() {
                progressBar.setVisibility(View.GONE);
            }
        });
    }

    /**
     * 显示错误信息
     *
     * @param content
     * @param onClickListener
     */
    private void showErrorTv(final String content, final View.OnClickListener onClickListener) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                errorTv.setText(content);
                errorTv.setOnClickListener(onClickListener);
                errorTv.setVisibility(View.VISIBLE);
            }
        });
    }

    /**
     * 隐藏错误信息
     */
    private void hideErrorTv() {
        handler.post(new Runnable() {
            @Override
            public void run() {
                errorTv.setVisibility(View.GONE);
            }
        });
    }

    /**
     * 请求同步数据
     */
    private void requestSchedules() {
        hasRequestSchedules = true;

        showProgressBar();

        PutDataMapRequest putDataMapRequest = PutDataMapRequest.create(Path.CMD_SYNC);
        putDataMapRequest.getDataMap().putString("timestamp", System.currentTimeMillis() + "");
        PendingResult pendingResult = Wearable.DataApi.putDataItem(googleApiClient, putDataMapRequest.asPutDataRequest());

    }

    /**
     * 与手机连接状态发生变化
     *
     * @param connected
     */
    @Override
    public void onConnectChanged(final boolean connected, Node peer) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                if (connected) {
                    hideErrorTv();
                    requestSchedules();
                } else {
                    hideProgressBar();
                    scheduleListAdapter.clearData();
                    showErrorTv(getString(R.string.check_connect), null);
                }
            }
        });
    }

    private ObserverIfaces.OnSyncSchedulesListener onSyncSchedulesListener = new ObserverIfaces.OnSyncSchedulesListener() {
        @Override
        public void onSync(final List<WearSchedule> wearSchedules) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    hideProgressBar();
                    hideErrorTv();
                    if (wearSchedules != null) {
                        scheduleListAdapter.setData(wearSchedules);

                        if (wearSchedules.size() == 0) { // 无计划安排
                            showErrorTv(getString(R.string.non_schedules), null);
                        }
                    }
                }
            });
        }
    };
}
